#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<signal.h>
#include<sys/wait.h>

volatile int wait_flag=1;

void soft_interrupt_3_handler(int sig)
{
    wait_flag=0;
    write(STDOUT_FILENO, "Register a signal handler for signal 3.\n", 41);

}

void soft_interrupt_16_handler(int sig)
{
    wait_flag=0;
}

void soft_interrupt_17_handler(int sig)
{
    wait_flag=0;
}

int main()
{
    pid_t pid1=-1,pid2=-1;

    //register signal handler function
    signal(SIGUSR1,soft_interrupt_3_handler);
    kill(getpid(),SIGUSR1);
    while(wait_flag)
    {
        sleep(1);
    }
    wait_flag=1;
    
    while(pid1==-1)
    {
        pid1 = fork();
        if(pid1==0)
        {
            //child 1
            signal(SIGUSR1,soft_interrupt_16_handler);
            kill(getpid(),SIGUSR1);
            while(wait_flag)
            {
                sleep(1);
            }
            wait_flag=1;
            printf("Process %d got a signal.\n", getpid());
            exit(0);
        } else if (pid1>0)
        {
            while(pid2==-1)
            {
                pid2 = fork();
                if(pid2>0)
                {

                    sleep(5);
                    kill(pid1,SIGTERM);
                    printf("Child process 1 is killed by parent!!\n");

                    printf("Process %d got a signal.\n", getpid());
                    
                    kill(pid2,SIGTERM);
                    printf("Child process 2 is killed by parent!!\n");

                    wait(NULL);
                    wait(NULL);

                    printf("Parent process exit normally!\n");
                    exit(0);
                } else if (pid2==0)
                {
                    signal(SIGUSR1,soft_interrupt_17_handler);
                    kill(getpid(),SIGUSR1);
                    while (wait_flag)
                    {
                        sleep(1);
                    }
                    wait_flag=1;
                    printf("Process %d got a signal.\n", getpid());
                    exit(0);
                }
            }
        }
    }

    return 0;
}

